﻿using System.IO;
using System.Text;
using System.Threading;
using Core.Common.Monitor;
using Core.Expansion;
using Newtonsoft.Json.Linq;
using Tool.Web.HttpHelper;
using static Core.Common.Global;

namespace Core.Monitors
{
	internal class YoutubeLive : Tool.Common.Monitor
	{
		//AIzaSyCaK1n7_3lEMsKkr9AAlzX3NkxXxiFEZk4
		public static string key;
		private string name;
		private int status = -1;

		public YoutubeLive(object flag) : base(flag)
		{
			ClearAllCloseEvent();
			ClearAllStartEvent();
			CloseEvent += () => CQ.Log($"关闭了对{flag}的油管直播监控任务");
			StartEvent += () => CQ.Log($"开启了对{flag}的油管直播监控任务");
		}

		protected override void Handle()
		{
			CQ.Log($"status:{status} name:{name}");
			//https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={flag}&type=video&eventType=live&key={key}
			//UCdn5BQ06XqgXoAxIhbqw5Rg
			var data = HttpNet.Get($"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={flag}&type=video&eventType=live&key={key}", proxy: Proxy);
			if (data.Length == 0)
			{
				CQ.Log($"本次{flag}油管直播无数据");
				return;
			}
			JObject json = JObject.Parse(Encoding.UTF8.GetString(data));
			JArray items = json["items"] as JArray;
			if (status == -1)
			{
				if (items.Count == 0) status = 0;
				else
				{
					status = 1;
					name = items[0]["snippet"]["channelTitle"].ToString();
				}
				return;
			}
			else
			{
				int temp_status = items.Count == 0 ? 0 : 1;
				if (temp_status != status)
				{
					status = temp_status;
					string msg;
					if (status == 0) msg = $"你订阅的{name}下播了";
					else
					{
						name = items[0]["snippet"]["channelTitle"].ToString();
						string uri = items[0]["snippet"]["thumbnails"]["default"]["url"].ToString();
						var path = ImagePath + flag + ".jpg";
						File.WriteAllBytes(path, HttpNet.Get(uri, proxy: Proxy));
						msg = $"你订阅的{name}开播了\n{items[0]["snippet"]["title"]}{CQ.Code_Image(path.HandleImagePath())}{items[0]["snippet"]["description"]}";
					}
					MonitorInfo monitorInfo = YtbLiveInfo.Find((e) => e.flag == (string)flag);
					lock (monitorInfo)
					{
						foreach (MonitorItem item in monitorInfo.item)
						{
							if (item.status == 1)
							{
								if (item.type == 0)
									CQ.SendGroupMessage(item.num, msg);
								if (item.type == 1)
									CQ.SendPrivateMessage(item.num, msg);
								Thread.Sleep(1000);
							}
						}
					}
				}
			}
		}
	}
}
